<?php
class controller_admin_index extends system_user_control {	

	public function init() {
		parent::init();
		$this->layout()->setLayout('panelLayout');
	}
	
	public function action_index() {
		if($this->adminLogin()) {
			return ;
		}
		/**
		 * 选择语言
		 */
		if($this->getRequest()->isPost() && ($language = $this->_post('language'))) {
			system_user_instance::getInstance()->getSession()->setLanguage($language);
			$this->user->setLang($language);
			$this->user->update();
			$this->_go();
		}
		$this->render();
	}
	
	public function action_picture() {
		if($this->adminLogin()) {
			return ;
		}
		$this->render();
	}
		
	public function action_login() {
		$this->view->request = $this->getRequest();
		$this->view->error = array();
		if($this->getRequest()->isPost()) {
			$this->referer = trim($this->_post('referer'));
			$lang = trim($this->_post('language'));
			try {
				if($this->_post('changeLanguage')) {
					system_user_instance::getInstance()->getSession()->setLanguage($lang);
					system_nav_language::getInstance()->setLanguage($lang);
				} else {
					if(!system_captcha::auth($this->_post('validCode'), self::$_namespace)) {
						$this->view->error['validCode'] = 'Valid code is not matched.';
					}
					
					$account = trim($this->_post('account'));
					$password = trim($this->_post('password'));
					$concept = new system_user_concept();
					if(!($row = $concept->fetch(array('identity=?' => $account)))) {
						$this->view->error['auth'] = 'Authenticate failed.';
					}
					if($row && !$row->auth($password)) {
						$this->view->error['auth'] = 'Authenticate failed.';
					}
					
					if(count($this->view->error)==0) {					
						$secure = system_user_instance::getInstance()->getSession()
								->setId($row->getId())
								->setIdentity($account)
								->setSecurity(intval($this->getRequest()->getPost('secure')))
								->setLanguage($lang);
						if($this->_post('remember')) {
							$secure->setExpirationSeconds(system_session::getOptions('remember_me_seconds'));
						}
						
						$row->setSecure($secure->getSecurity());
						$row->setLang($lang);
						$row->setLastupip($this->getRequest()->getClientIp());
						$row->setLastupdate(system_date::timestamp());
						$row->update();
						$this->_go();
					}
				}
				$this->view->referer = $this->referer;
			} catch (Exception $e) {
				$this->view->exception = $e;
			}			
		}
		$this->layout()->disableLayout();
		$this->render();
	}
	
	public function action_logout() {
		system_user_instance::getInstance()->getSession()->logout();
		$this->_go();
	}
	
	public function action_error() {
		if(!$this->view->exception) {
			$this->view->exception = $this->getResponse()->getException();
		}
		$this->layout()->setLayout('layout');
		$this->render();
	}
	
	public function action_captcha() {
		system_captcha::getInstance(self::$_namespace)->setCode()->display();
	}
}
